#!/usr/bin/env bash
#########################################################################
# File Name   : FILENAME
# Author      : seadog
# mail        : seadog0514@163.com
# Version     : 0.1
# Created Time: DATETIME
#########################################################################

#
#
# Usage:

{
  set -euo pipefail
  # set -E
  #     If set, any trap on ERR is inherited by shell functions, command
  #     substitutions, and commands executed in a subshell environment.

  export TZ="Asia/Shanghai"
  APP_ROOT=$(dirname "$(readlink -fm "$0")")
  cd "${APP_ROOT}"

  exec &> >(tee -a "/tmp/build.log")

  function usage() {
    echo """

    """
  }

  function logme() {
    local LOGTYPE=$1
    shift
    local MSGC=$*
    local LOGTIME
    LOGTIME="$(date '+%Y-%m-%d %H:%M:%S')"
    case $LOGTYPE in
      i) echo -e "$LOGTIME => INFO  ¦ ${MSGC}" ;;
      d) echo -e "\e[0;96m$LOGTIME => DEBUG ¦ ${MSGC}\e[00m" ;;
      w) echo -e "\e[0;33m$LOGTIME => WARN  ¦ ${MSGC}\e[00m" ;;
      e) echo -e "\e[0;31m$LOGTIME => ERROR ¦ ${MSGC}\e[00m" && return 1 ;;
    esac
  }

  # !!# trap
  function cleanup {
    echo 报错时收尾代码
    exit 1
  }
  trap "{ cleanup; }" SIGINT SIGTERM ERR # EXIT

  # !!# spin bar
  function start_spin() {
    SPIN_PID="false"
    if [[ ${#@} -ne 1 ]]; then
      echo "invalid para, usage: start_spin 'message'"
      exit 1
    fi

    START_MESSAGE="$1 ..."

    function do_start_spin() {
      local FRAME
      local FRAME_INTERVAL
      local k

      # FRAME=("-" "\\" "|" "/")
      # FRAME_INTERVAL=0.15
      FRAME=("⠋" "⠙" "⠹" "⠸" "⠼" "⠴" "⠦" "⠧" "⠇" "⠏")
      FRAME_INTERVAL=0.1

      k=0
      while true; do
        echo -ne "\\r[ ${FRAME[k]} ] $START_MESSAGE"
        sleep $FRAME_INTERVAL
        len=${#FRAME[@]}
        k=$(((k + 1) % len))
      done

      # tput cnorm -- normal
    }
    do_start_spin "$1" &
    SPIN_PID=$!
  }

  function stop_spin() {
    local exit_code
    local msg
    if [[ ${#@} -lt 1 || ${#@} -gt 2 ]]; then
      echo "invalid para, usage: stop_spin 'message' 'exit_code'"
      exit 1
    elif [[ ${#@} -eq 1 ]]; then
      exit_code=0
    elif [[ ${#@} -eq 2 ]]; then
      exit_code=$2
    fi
    msg=$1

    if [[ ! $SPIN_PID =~ [0-9]+ ]]; then
      echo "SPIN_PID is not valid: $SPIN_PID"
      exit 8
    fi

    kill "$SPIN_PID"
    START_MESSAGE="${START_MESSAGE//[^[:space:]]/ }    "
    echo -ne "\\r[ ✓ ] ${START_MESSAGE}"
    if [[ $exit_code -le 0 ]]; then
      echo -ne "\\r[ ✓ ] ${msg}\\n"
    else
      echo -ne "\\r[ ✗ ] ${msg}\\n"
    fi
  }

  # start_spin 'start'
  # sleep 3
  # stop_spin 'done'
}
